import tkinter as tk
from tkinter import ttk, filedialog, scrolledtext, BooleanVar
import logging

logger = logging.getLogger(__name__)


class ConfigDialog:
    def __init__(self, main_window):
        self.main_window = main_window
        self.dialog = tk.Toplevel(main_window.root)
        self.dialog.title("系统配置")
        self.dialog.geometry("600x500")

        # 计算窗口居中位置
        screen_width = self.dialog.winfo_screenwidth()
        screen_height = self.dialog.winfo_screenheight()
        x = (screen_width - 600) // 2
        y = (screen_height - 500) // 2
        self.dialog.geometry(f"600x500+{x}+{y}")

        # 主框架（包含notebook和按钮）
        main_frame = ttk.Frame(self.dialog)
        main_frame.pack(fill=tk.X, expand=True, padx=5, pady=5)

        # 创建Notebook用于分页
        notebook = ttk.Notebook(main_frame)
        notebook.pack(fill=tk.BOTH, expand=True)

        # 系统设置页
        sys_frame = ttk.Frame(notebook)
        notebook.add(sys_frame, text="系统设置")

        # 上传设置页
        upload_frame = ttk.Frame(notebook)
        notebook.add(upload_frame, text="上传设置")

        # 下载设置页
        download_frame = ttk.Frame(notebook)
        notebook.add(download_frame, text="下载设置")

        # 部署设置页
        deploy_frame = ttk.Frame(notebook)
        notebook.add(deploy_frame, text="部署设置")

        # 保存按钮
        def save_config():
            self.main_window.config.set('sys', 'server_file', server_file_entry.get())
            self.main_window.config.set('sys', 'develop_mode', str(develop_mode_var.get()))
            self.main_window.config.set('sys', 'develop_password', develop_pass_entry.get())
            self.main_window.config.set('sys', 'batch_execute', str(batch_execute_var.get()))
            self.main_window.config.set('sys', 'auto_load_servers', str(auto_load_servers_var.get()))
            self.main_window.config.set('sys', 'auto_select_all_servers', str(auto_select_all_servers_var.get()))
            self.main_window.config.set('sys', 'auto_connect_servers', str(auto_connect_servers_var.get()))

            # 保存上传设置
            self.main_window.config.set('upload', 'default_files', default_upload_files_text.get(1.0, tk.END).strip())
            self.main_window.config.set('upload', 'default_remote_dir', default_remote_dir_entry.get())

            # 保存下载设置
            self.main_window.config.set('download', 'default_files', default_download_files_text.get(1.0, tk.END).strip())
            self.main_window.config.set('download', 'default_save_path', default_save_path_entry.get())

            for var_name in deploy_vars:
                self.main_window.config.set('deploy', var_name, str(deploy_vars[var_name].get()))

            # 保存网卡名称
            self.main_window.config.set('deploy', 'network_interface', network_interface_entry.get())

            # 保存SSH隧道配置
            self.main_window.config.set('ssh_tunnel', 'enable', str(enable_ssh_tunnel_config_var.get()))
            self.main_window.config.set('ssh_tunnel', 'jump_host', jump_host_server_config_entry.get())
            self.main_window.config.set('ssh_tunnel', 'username', jump_host_username_config_entry.get())
            self.main_window.config.set('ssh_tunnel', 'password', jump_host_password_config_entry.get())

            self.dialog.destroy()
            self.main_window.show_message("系统配置已保存")

        # 修改保存按钮的布局方式
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, padx=10, pady=10)
        ttk.Button(button_frame, text="保存", command=save_config).pack(padx=2, pady=2)

        # 系统设置内容
        ttk.Label(sys_frame, text="服务器信息文件默认路径:").grid(row=0, column=0, sticky="w", padx=5, pady=5)
        server_file_entry = ttk.Entry(sys_frame, width=40)
        server_file_entry.grid(row=0, column=1, sticky="ew", padx=5, pady=5)
        server_file_entry.insert(0, self.main_window.config.get('sys', 'server_file'))

        # 自动加载服务器选项
        auto_load_servers_var = BooleanVar(value=self.main_window.config.getboolean('sys', 'auto_load_servers', default=False))
        ttk.Checkbutton(sys_frame, text="自动加载服务器", variable=auto_load_servers_var).grid(row=1, column=0,
                                                                                               columnspan=2, sticky="w",
                                                                                               padx=5, pady=5)

        # 自动全选服务器选项（依赖于自动加载服务器）
        auto_select_all_servers_var = BooleanVar(value=self.main_window.config.getboolean('sys', 'auto_select_all_servers', default=False))
        auto_select_all_checkbutton = ttk.Checkbutton(sys_frame, text="自动全选服务器", variable=auto_select_all_servers_var)
        auto_select_all_checkbutton.grid(row=2, column=0, columnspan=2, sticky="w", padx=5, pady=5)

        # 自动连接服务器选项（依赖于自动全选服务器）
        auto_connect_servers_var = BooleanVar(value=self.main_window.config.getboolean('sys', 'auto_connect_servers', default=False))
        auto_connect_servers_checkbutton = ttk.Checkbutton(sys_frame, text="自动连接服务器", variable=auto_connect_servers_var)
        auto_connect_servers_checkbutton.grid(row=3, column=0, columnspan=2, sticky="w", padx=5, pady=5)

        # Develop模式和密码放在同一行
        develop_frame = ttk.Frame(sys_frame)
        develop_frame.grid(row=4, column=0, columnspan=2, sticky="ew", padx=5, pady=5)
        
        develop_mode_var = BooleanVar(value=self.main_window.config.getboolean('sys', 'develop_mode'))
        ttk.Checkbutton(develop_frame, text="Develop模式", variable=develop_mode_var).pack(side=tk.LEFT)
        
        ttk.Label(develop_frame, text="默认密码:").pack(side=tk.LEFT, padx=(10, 0))
        develop_pass_entry = ttk.Entry(develop_frame, show="*", width=20)
        develop_pass_entry.pack(side=tk.LEFT, padx=(5, 0))
        develop_pass_entry.insert(0, self.main_window.config.get('sys', 'develop_password'))

        batch_execute_var = BooleanVar(value=self.main_window.config.getboolean('sys', 'batch_execute'))
        ttk.Checkbutton(sys_frame, text="默认启用批量执行命令", variable=batch_execute_var).grid(row=5, column=0,
                                                                                                 columnspan=2,
                                                                                                 sticky="w", padx=5,
                                                                                                 pady=5)

        # 定义依赖关系的回调函数
        def on_auto_load_servers_change():
            if auto_load_servers_var.get():
                auto_select_all_checkbutton.config(state=tk.NORMAL)
            else:
                auto_select_all_servers_var.set(False)
                auto_select_all_checkbutton.config(state=tk.DISABLED)
                auto_connect_servers_var.set(False)
                auto_connect_servers_checkbutton.config(state=tk.DISABLED)

        def on_auto_select_all_servers_change():
            if auto_select_all_servers_var.get():
                auto_connect_servers_checkbutton.config(state=tk.NORMAL)
            else:
                auto_connect_servers_var.set(False)
                auto_connect_servers_checkbutton.config(state=tk.DISABLED)

        # 绑定回调函数
        auto_load_servers_var.trace('w', lambda *args: on_auto_load_servers_change())
        auto_select_all_servers_var.trace('w', lambda *args: on_auto_select_all_servers_change())

        # 初始化状态
        on_auto_load_servers_change()
        on_auto_select_all_servers_change()

        # --- 跳板机（SSH隧道）默认配置分组 ---
        ssh_tunnel_group = ttk.LabelFrame(sys_frame, text="SSH隧道（跳板机）默认配置", padding=(10, 5))
        ssh_tunnel_group.grid(row=6, column=0, columnspan=2, sticky="ew", padx=5, pady=10)

        enable_ssh_tunnel_config_var = BooleanVar(value=self.main_window.config.getboolean('ssh_tunnel', 'enable', default=False))
        ttk.Checkbutton(
            ssh_tunnel_group, text="默认启用SSH隧道", variable=enable_ssh_tunnel_config_var,
            command=lambda: _on_config_ssh_tunnel_toggle()
        ).grid(row=0, column=0, sticky="w", padx=5, pady=5)

        ttk.Label(ssh_tunnel_group, text="踏板机服务器:").grid(row=1, column=0, sticky="e", padx=5, pady=2)
        jump_host_server_config_entry = ttk.Entry(ssh_tunnel_group, width=30)
        jump_host_server_config_entry.grid(row=1, column=1, sticky="ew", padx=5, pady=2)
        jump_host_server_config_entry.insert(0, self.main_window.config.get('ssh_tunnel', 'jump_host', default=''))

        ttk.Label(ssh_tunnel_group, text="踏板机用户:").grid(row=2, column=0, sticky="e", padx=5, pady=2)
        jump_host_username_config_entry = ttk.Entry(ssh_tunnel_group, width=20)
        jump_host_username_config_entry.grid(row=2, column=1, sticky="ew", padx=5, pady=2)
        jump_host_username_config_entry.insert(0, self.main_window.config.get('ssh_tunnel', 'username', default=''))

        ttk.Label(ssh_tunnel_group, text="踏板机密码:").grid(row=3, column=0, sticky="e", padx=5, pady=2)
        jump_host_password_config_entry = ttk.Entry(ssh_tunnel_group, show="*", width=20)
        jump_host_password_config_entry.grid(row=3, column=1, sticky="ew", padx=5, pady=2)
        jump_host_password_config_entry.insert(0, self.main_window.config.get('ssh_tunnel', 'password', default=''))

        def _on_config_ssh_tunnel_toggle():
            state = tk.NORMAL if enable_ssh_tunnel_config_var.get() else tk.DISABLED
            jump_host_server_config_entry.config(state=state)
            jump_host_username_config_entry.config(state=state)
            jump_host_password_config_entry.config(state=state)

        # 初始设置SSH隧道控件状态
        _on_config_ssh_tunnel_toggle()

        # 上传设置内容
        ttk.Label(upload_frame, text="文件/文件夹:").grid(row=0, column=0, sticky="w", padx=5, pady=5)
        default_upload_files_text = scrolledtext.ScrolledText(upload_frame, height=6, width=50, wrap=tk.WORD)
        default_upload_files_text.grid(row=0, column=1, sticky="ew", padx=5, pady=5)
        default_upload_files_text.insert(tk.END, self.main_window.config.get('upload', 'default_files', default=''))

        # 上传设置按钮框架
        upload_button_frame = ttk.Frame(upload_frame)
        upload_button_frame.grid(row=0, column=2, padx=5, pady=5, sticky="ns")
        
        def browse_upload_file():
            file_paths = filedialog.askopenfilenames(title="选择默认上传文件")
            if file_paths:
                default_upload_files_text.delete(1.0, tk.END)
                default_upload_files_text.insert(tk.END, "\n".join(file_paths))
        
        def browse_upload_folder():
            folder_path = filedialog.askdirectory(title="选择默认上传文件夹")
            if folder_path:
                default_upload_files_text.delete(1.0, tk.END)
                default_upload_files_text.insert(tk.END, folder_path)
        
        ttk.Button(upload_button_frame, text="浏览文件", command=browse_upload_file).pack(side=tk.TOP, fill=tk.X, pady=2)
        ttk.Button(upload_button_frame, text="浏览文件夹", command=browse_upload_folder).pack(side=tk.TOP, fill=tk.X, pady=2)

        ttk.Label(upload_frame, text="远程上传目录:").grid(row=1, column=0, sticky="w", padx=5, pady=5)
        default_remote_dir_entry = ttk.Entry(upload_frame, width=40)
        default_remote_dir_entry.grid(row=1, column=1, sticky="ew", padx=5, pady=5)
        default_remote_dir_entry.insert(0, self.main_window.config.get('upload', 'default_remote_dir', default='/tmp'))

        # 下载设置内容
        ttk.Label(download_frame, text="下载文件或目录:").grid(row=0, column=0, sticky="w", padx=5, pady=5)
        default_download_files_text = scrolledtext.ScrolledText(download_frame, height=6, width=50, wrap=tk.WORD)
        default_download_files_text.grid(row=0, column=1, sticky="ew", padx=5, pady=5)
        default_download_files_text.insert(tk.END, self.main_window.config.get('download', 'default_files', default=''))

        ttk.Label(download_frame, text="保存路径:").grid(row=1, column=0, sticky="w", padx=5, pady=5)
        default_save_path_entry = ttk.Entry(download_frame, width=40)
        default_save_path_entry.grid(row=1, column=1, sticky="ew", padx=5, pady=5)
        default_save_path_entry.insert(0, self.main_window.config.get('download', 'default_save_path', default=''))
        
        def browse_default_save_path():
            path = filedialog.askdirectory(title="选择默认保存路径")
            if path:
                default_save_path_entry.delete(0, tk.END)
                default_save_path_entry.insert(0, path)
        
        ttk.Button(download_frame, text="浏览", command=browse_default_save_path).grid(row=1, column=2, padx=5, pady=5)

        # 部署设置内容
        deploy_vars = {
            'configure_hostname': BooleanVar(value=self.main_window.config.getboolean('deploy', 'configure_hostname')),
            'configure_hosts': BooleanVar(value=self.main_window.config.getboolean('deploy', 'configure_hosts')),
            'configure_dns': BooleanVar(value=self.main_window.config.getboolean('deploy', 'configure_dns')),
            'sync_time': BooleanVar(value=self.main_window.config.getboolean('deploy', 'sync_time')),
            'load_image': BooleanVar(value=self.main_window.config.getboolean('deploy', 'load_image')),
            'register_node': BooleanVar(value=self.main_window.config.getboolean('deploy', 'register_node'))
        }

        # 只保留网卡名称输入框
        network_interface_entry = ttk.Entry(deploy_frame)
        network_interface_entry.grid(row=4, column=1, sticky="w", padx=5, pady=2)
        try:
            network_interface_entry.insert(0, self.main_window.config.get('deploy', 'network_interface'))
        except:
            network_interface_entry.insert(0, 'eth0')

        deploy_options = [
            ("默认配置主机名", 'configure_hostname'),
            ("默认配置hosts文件", 'configure_hosts'),
            ("默认配置DNS解析", 'configure_dns'),
            ("默认同步时间", 'sync_time'),
            ("默认加载镜像", 'load_image'),
            ("默认节点注册", 'register_node')
        ]

        for i, (text, var_name) in enumerate(deploy_options):
            ttk.Checkbutton(deploy_frame, text=text, variable=deploy_vars[var_name]).grid(
                row=i, column=0, sticky="w", padx=5, pady=2)

        network_interface_entry = ttk.Entry(deploy_frame)
        network_interface_entry.grid(row=4, column=1, sticky="w", padx=5, pady=2)
        try:
            network_interface_entry.insert(0, self.main_window.config.get('deploy', 'network_interface'))
        except:
            network_interface_entry.insert(0, 'eth0')

        deploy_options = [
            ("默认配置主机名", 'configure_hostname'),
            ("默认配置hosts文件", 'configure_hosts'),
            ("默认配置DNS解析", 'configure_dns'),
            ("默认同步时间", 'sync_time'),
            ("默认加载镜像", 'load_image'),
            ("默认节点注册", 'register_node')
        ]

        for i, (text, var_name) in enumerate(deploy_options):
            ttk.Checkbutton(deploy_frame, text=text, variable=deploy_vars[var_name]).grid(
                row=i, column=0, sticky="w", padx=5, pady=2) 